<template>
  <el-card v-loading="loading"
           element-loading-text="正在思考中..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="chat-box" ref="chatBox">
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <div v-if="msg.type === 'user'" class="user-message user">
          <img :src="avatar" alt="User" class="user-avatar"/>
          <div class="message-content user-message-content">{{ msg.content }}</div>
        </div>
        <div v-if="msg.type === 'bot'" class="bot-message">
          <img :src="avatar_bot" alt="Bot" class="avatar"/>
          <markdown :source="msg.content" class="message-content bot-message-content"></markdown>
        </div>
      </div>
    </div>
    <div class="input-area">
      <img :src="avatar" alt="User" class="avatar"/>
      <el-input
          v-model="input"
          placeholder="请输入您的问题"
          @keyup.enter.native="sendMessage"
          class="input-field"
          :style="{ maxWidth: 'calc(100% - 100px)' }"
      ></el-input>
      <el-button type="primary" :disabled="loading" @click="sendMessage">发送</el-button>
    </div>
    <!--    <el-card class="tools-card">-->
    <!--      <div v-for="(item, index) in mcpTools" :key="index">-->
    <!--        <el-tag class="tool-tag">{{ index + 1 }}、{{ item }}</el-tag>-->
    <!--      </div>-->
    <!--    </el-card>-->
  </el-card>
</template>

<script>
import Markdown from "vue-markdown";

const WSClient = require('./ws-client');
let wsClient;

export default {
  name: 'AIChat',
  components: {Markdown},
  data() {
    return {
      input: '',
      messages: [],
      avatar: require('./avatar/user.png'),
      avatar_bot: require('./avatar/bot.png'),
      loading: true,
      // mcp
      mcpTools: []
    };
  },
  beforeDestroy() {
    wsClient.close()
  },
  mounted() {
    // wsClient = new WSClient(`ws://${window.location.host}/mcp/ws`);
    wsClient = new WSClient(`ws://127.0.0.1:9802/mcp/ws`);
    wsClient.setOnOpen(() => {
      if (this.messages.length === 0) {
        wsClient.send({
          action: 'listTools',
          payload: {}
        })
      }
    });

    wsClient.setOnMessage((msg) => {
      console.log('服务端消息', msg)
      if (!msg) {
        return
      }
      let data = {}
      try {
        data = JSON.parse(msg)
        let content = '你好！很高兴见到你！我可以帮你处理以下问题。\n'
        for (let i = 0; i < data.length; i++) {
          const {description} = data[i]
          this.mcpTools.push(description)
          content += `- ${description} \n`
        }
        this.messages.push({
          type: 'bot', content
        });
      } catch (e) {
        data = {msg}
        this.messages.push({
          type: 'bot', content: `${msg}`
        });
        this.scrollToBottom();
      }
      console.log('服务端数据', data)
      this.loading = false
    });
  },
  methods: {
    sendMessage() {
      this.loading = true
      console.log('消息:', this.input)
      if (this.input.trim() === '') return;

      this.messages.push({type: 'user', content: this.input});
      const userInput = this.input;
      this.input = '';

      wsClient.send({
        action: 'chat',
        payload: {
          prompt: userInput
        }
      })

      this.scrollToBottom();
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
.chat-box {
  height: calc(100vh - 260px);
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}

.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.message {
  margin: 10px 0;
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: space-between;
}

.user-message, .bot-message {
  margin-top: 2px;
  display: flex;
  align-items: center;
}

.avatar {
  border-radius: 10%;
  margin-right: 10px;
  width: 38px;
  height: 38px;
}

.user {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
}

.user-avatar {
  border-radius: 10%;
  margin-left: 10px;
  width: 38px;
  height: 38px;
}

.input-field {
  flex: 1;
  margin-right: 10px;
  max-width: calc(100% - 100px);
}

.message-content {
  max-width: 100%; /* 确保消息内容框不超过聊天框宽度 */
  background-color: #f0f0f0; /* 随意选择背景颜色 */
  border-radius: 5px; /* 圆角 */
  padding: 10px; /* 内边距 */
  overflow-wrap: break-word; /* 使长文本换行 */
  white-space: normal; /* 允许文本在标签内换行 */
  word-wrap: break-word; /* 兼容旧版浏览器 */
}

.user-message-content {
  background-color: #d1e7dd; /* 用户消息的背景颜色 */
}

.bot-message-content {
  background-color: #cfe2ff; /* 机器人消息的背景颜色 */
}

.tools-card {
  margin-top: 24px;
  padding-top: 12px;
}

.tool-tag {
  margin-bottom: 8px;
}
</style>
